package com.example.listviewtest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private String[] data = { "Apple", "Banana", "Orange", "Watermelon",
            "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango",
            "Apple", "Banana", "Orange", "Watermelon", "Pear", "Grape",
            "Pineapple", "Strawberry", "Cherry", "Mango" };
    private List<Fruit> list = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 三个参数：上下文、ListView的子项id(android内置文件)、数据
//        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
//                MainActivity.this, android.R.layout.simple_list_item_1, data);
//        ListView listView = (ListView) findViewById(R.id.list_view);
//        listView.setAdapter(adapter);
        // 获取数据
        InitFruit();
        // 适配器
        FruitAdapter fd = new FruitAdapter(MainActivity.this,R.layout.fruit_item,list);
        ListView listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(fd);
        // 给ListView的所有子项绑定点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //list集合中的get：返回列表中指定位置的元素。
                Fruit fruit = list.get(position);
                Toast.makeText(MainActivity.this, fruit.getName(),
                        Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void InitFruit(){
        for (int i = 0; i < 2; i++) {
            Fruit f1 = new Fruit("apple1",R.drawable.img);
            list.add(f1);
            Fruit f2 = new Fruit("apple2",R.drawable.img);
            list.add(f2);
            Fruit f3 = new Fruit("apple3",R.drawable.img);
            list.add(f3);
            Fruit f4 = new Fruit("apple4",R.drawable.img);
            list.add(f4);
            Fruit f5 = new Fruit("apple5",R.drawable.img);
            list.add(f5);
            Fruit f6 = new Fruit("apple6",R.drawable.img);
            list.add(f6);
            Fruit f7 = new Fruit("apple7",R.drawable.img);
            list.add(f7);
            Fruit f8 = new Fruit("apple8",R.drawable.img);
            list.add(f8);
        }
    }
}